<template>
	<view class="locat_main">
		<!-- <view class="search_box">
			<view class="search" @click="goLocation">
				<uni-icons type="search" color="#999" size="22"></uni-icons><span class="title_label">地点搜索</span>
			</view>	
		</view> -->
		<view class="map_back" style="width: 100%; height: 40%;background-color: aliceblue;">
			<map id="map" v-if="myLongitude" style="width: 100%; height: 100%" :include-points="includePoints"
				:show-location="true" :enable-3D="true" :show-compass="true" :latitude="myLatitude"
				:longitude="myLongitude" :circles="circles" :markers="markers" :scale="scale"></map>
		</view>
		<view class="locat_content">
			<view class="tip_label">
				当前位置
			</view>
			<view class="current_position">
				<view class="current_position_left">
					<view class="left_address">
						{{engineerSignVo.signInAddress}}
					</view>
					<view class="left_tip">
						{{engineerSignVo.signInProvince+engineerSignVo.signInCity+engineerSignVo.signInArea}}
					</view>
				</view>
				<view class="current_position_right" @click="getLocation">
					<uni-icons type="location" color="#007cff" size="24"></uni-icons>重新定位
				</view>
			</view>
			<view v-if="setSignObj?.signType==2">
				<view class="tip_label">
					上传签到照片({{imgarr.length}}/6)
				</view>
				<view class="example-body">
					<uni-file-picker limit="6" :sourceType="['camera']" @select="onsuccessImg" :auto-upload="false"
						@delete="ondeleteImg" file-mediatype="image" v-model="imgarr">
						<view class="pic_text">
							<uni-icons type="camera-filled" color="#999" size="34"></uni-icons>
							<p>拍照</p>
						</view>
					</uni-file-picker>
				</view>
			</view>
		</view>
		<view class="btn_word">
			<button type="primary" class="btn_bor" @click="onSubmit">签到</button>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import {
		ref,
		reactive,
		nextTick, onMounted
	} from "vue"
	import _ from "lodash"
	import { onUnload, onLaunch, onLoad, onHide } from '@dcloudio/uni-app'
	import apiOrder from "@/util/network_api/apiOrder.js"
	import apiUpload from "@/util/network_api/upload.js"
	import store from '@/store_network/index.js'
	const workId = ref()
	const address = ref()//客户地址
	const signRange = ref(0)//签到范围 米
	const myLatitude = ref(0)//当前位置纬度
	const myLongitude = ref(0)//当前位置经度
	const location = ref([])//[纬度，经度]     客户经纬度 112.570412, 37.894241
	const includePoints = ref([{ longitude: 0, latitude: 0 }, { longitude: 0, latitude: 0 }])
	const scale = ref(16)
	// 通过onLoad接收数据
	onLoad((e) => {
		if (e) {
			workId.value = e.workId
			engineerSignVo.value.dispatchEngineerId = e.dispatchEngineerId
			address.value = e.address
			markers.value[0].callout.content = address.value
			Promise.all([NetworkEmpSignSet(), getLocation(), goLocation()],).then(() => { })
		}

	})
	onUnload(() => {
		uni.hideLoading()
	})
	/*
	 signType签到方式:1-定位签到，2-拍照签到
	 enableSecurityWatermark 是否启用拍照防伪作弊水印:false-不启用，true-启用，当sign tvpe-2时牛效
	 signRange 签到范围，单位:米，当signType=1时生效
	 */
	const setSignObj = ref()
	const imgarr = ref([])
	const engineerSignVo = ref({
		"dispatchEngineerId": 0,//派单工程师ID
		"paths": [],//拍照签到附件路径
		"signInAddress": "",//签到地址-详情地址
		"signInArea": "",//签到地址-县/区
		"signInCity": "",//签到地址-市
		"signInProvince": "",//签到地址-省
		"signInTown": "",//签到地址-镇
		"signType": 1,//签到类型：1-定位签到，2-拍照签到,示例值(1)
		"signInDistance": 0,//签到距离，单位：米
	})
	// 地图上气泡提示
	const markers : any = ref([
		{
			id: 1,
			latitude: 0,
			longitude: 0,
			width: 25,//标注图标宽度
			height: 25,//标注图标高度
			iconPath: '/static/network/order/user.png',
			callout: {
				content: ' ',
				color: '#FFFFFF',//文字颜色
				fontSize: 20,//文字大小
				borderColor: '#69BFBE',//文字
				bgColor: '#69BFBE',//文字
				padding: 20,//文字
				borderRadius: 2,//文字
				display: 'ALWAYS',
				textAlign: 'center',
			},
			label: {
				content: '客户位置',
				color: '#007cff',
				fontSize: 24
			}
		},
		{
			id: 2,
			latitude: 0,
			longitude: 0,
			width: 25,//标注图标宽度
			height: 25,//标注图标高度
			iconPath: '/static/network/order/my.png',
			// callout: {
			// 	content: '当前位置',
			// 	color: '#FFFFFF',//文字颜色
			// 	fontSize: 20,//文字大小
			// 	borderColor: '#69BFBE',//文字
			// 	bgColor: '#69BFBE',//文字
			// 	padding: 20,//文字
			// 	borderRadius: 3,//文字
			// 	display: 'ALWAYS',
			// 	textAlign: 'center',
			// },
			label: {
				content: '当前位置',
				color: '#007cff',
				fontSize: 24
			}
		},
	])
	// 地图上圆形区域标识
	const circles = ref([
		{
			latitude: 0,//纬度
			longitude: 0,//经度
			color: '#69BFBE6A',//描边颜色
			fillColor: '#69BFBE6A',//范围颜色
			radius: 100,//半径
			strokeWidth: 2,//描边的宽度
		}
	])
	// 上传图片
	const onsuccessImg = (files) => {
		files.tempFiles.map(o => {
			imgarr.value.push(o)
		})
	}
	// 删除图片
	const ondeleteImg = (file) => {
		imgarr.value = imgarr.value.filter(o => {
			return o.uuid != file.tempFile.uuid
		})
	}
	// 签到
	const onSubmit = async () => {
		let s = getDistance(location.value, [myLatitude.value, myLongitude.value])
		if (s > signRange.value) {
			uni.showToast({
				title: '不在签到范围内!',
				icon: 'none'
			})
			return
		}
		uni.showLoading({
			title: '加载中...'
		})
		if (setSignObj.value?.signType == 2) {
			engineerSignVo.value.paths = []
			engineerSignVo.value.signType = 2
			if (imgarr.value.length > 0) {
				for (let i = 0; i < imgarr.value.length; i++) {
					let tmp = imgarr.value[i]
					await apiUpload.uploadOrderFile({ files: tmp.file }).then(res => {
						engineerSignVo.value.paths.push(res.data.rows[0])
					})
				}
			}
		} else {
			engineerSignVo.value.signType = 1
			engineerSignVo.value.signInDistance = signRange.value
		}
		await apiOrder.networkEngineerSign(engineerSignVo.value, workId.value).then(res => {
			if (res.code == 20000) {
				// uni.redirectTo({
				// 	url: '/pages_network/order/location/successfully/successfully'
				// })
				uni.redirectTo({
					url: '/pages_network/order/detail?workId=' + workId.value
				})
			}
		})
		uni.hideLoading()
	}
	// 获取签到设置
	const NetworkEmpSignSet = async () => {
		if (!workId.value) return
		await apiOrder.getNetworkEmpSignSet(workId.value).then(res => {
			if (res.code == 20000) {
				/*
				 signType签到方式:1-定位签到，2-拍照签到
				 enableSecurityWatermark 是否启用拍照防伪作弊水印:false-不启用，true-启用，当sign tvpe-2时牛效
				 signRange 签到范围，单位:米，当signType=1时生效
				 */
				setSignObj.value = res.data.row
				signRange.value = res.data.row.signRange
			}
		})

	}
	// 获取当前地址信息
	const getLocation = () => {
		uni.showLoading({
			title: '加载中...',
		})
		new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'gcj02',
				geocode: true,
				isHighAccuracy: true,
				success: (res) => {
					myLongitude.value = res.longitude
					myLatitude.value = res.latitude
					markers.value[1].latitude = res.latitude
					markers.value[1].longitude = res.longitude
					includePoints.value[1].latitude = res.latitude
					includePoints.value[1].longitude = res.longitude
					let s = getDistance(location.value, [myLatitude.value, myLongitude.value]) / 1000
					scale.value = setS(s)
					// 获取经纬度
					uni.request({
						url: `https://restapi.amap.com/v3/geocode/regeo?key=${store.state.key}&location=${res.longitude},${res.latitude}&radius=1&extensions=all&roadlevel=0`,
						method: 'GET',
					}).then(res2 => {
						let addressObj = (res2.data as { regeocode ?: any }).regeocode
						engineerSignVo.value.signInProvince = addressObj.addressComponent.province
						engineerSignVo.value.signInCity = addressObj.addressComponent.city
						engineerSignVo.value.signInArea = addressObj.addressComponent.township
						engineerSignVo.value.signInAddress = addressObj.pois[0].name
						uni.hideLoading()
					})
				},
				fail: (err) => {
					// uni.showToast({
					// 	title: '需要获取您的位置信息，请前往设置页面开启',
					// 	icon: 'none'
					// })
					uni.hideLoading()
					reject(err)
				}
			})
		})
	}

	function setS(s) {
		// 根据坐标计算出合理的比例尺寸
		let surface = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
		let num = 16
		for (let i in surface) {
			if (s > surface[i]) {
				num = (1 + Number(i))
			} else {
				num = 16
			}
		}
		return num
	}
	// 获取选择地址
	function getaddress() {
		uni.chooseLocation({
			success: function (res) {
				// 选择的地址
				// 解析
				uni.request({
					url: ` https://restapi.amap.com/v3/geocode/geo?key=${store.state.key}&address=${res.address}`,
					method: 'GET',
				}).then(res2 => {
					let addressObj = (res2.data as { regeocode ?: any }).regeocode
				})
			}
		});
	}
	//获取客户位置信息
	const goLocation = () => {
		uni.request({
			url: ` https://restapi.amap.com/v3/geocode/geo?key=${store.state.key}&address=${address.value}`,
			method: 'GET',
		}).then(res => {
			let addressObj : any = res.data
			location.value = [Number(Number(addressObj.geocodes[0].location.split(',')[1]).toFixed(6)), Number(Number(addressObj.geocodes[0].location.split(',')[0]).toFixed(6))]
			circles.value[0].latitude = location.value[0]
			circles.value[0].longitude = location.value[1]
			markers.value[0].latitude = location.value[0]
			markers.value[0].longitude = location.value[1]
			includePoints.value[0].latitude = location.value[0]
			includePoints.value[0].longitude = location.value[1]
			markers.value[0].latitude = location.value[0]
			circles.value[0].radius = signRange.value <= 0 ? 50 : signRange.value
			signRange.value = signRange.value <= 0 ? 50 : signRange.value

			// uni.navigateTo({
			// 	url: '/pages_network/order/location/chooseAddress?location=' + addressObj.geocodes[0].location+'&signRange='+signRange.value
			// })
		})
		// getaddress()
	}
	// 格式化经纬度
	const rad = (d : any) => {
		return (d * Math.PI) / 180.0
	}
	// 计算距离
	const getDistance = (point1 : any[], point2 : any[]) => {
		let [x1, y1] = point1
		let [x2, y2] = point2
		let Lat1 = rad(x1) // 纬度
		let Lat2 = rad(x2)
		let a = Lat1 - Lat2 //	两点纬度之差
		let b = rad(y1) - rad(y2) //	经度之差
		let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)))
		//	计算两点距离的公式
		s = s * 6378137.0 //	弧长等于弧度乘地球半径（半径为米）
		s = Math.round(s * 10000) / 10000 //	精确距离的数值
		return s
	}
</script>

<style lang="scss" scoped>
	.locat_main {
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		background-color: #fafafa;
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;

		.search_box {
			display: flex;
			align-items: center;
			padding: 24rpx;
			background-color: #fff;

			.search {
				flex: 1;
				padding: 0 12rpx;
				background-color: #f3f4f8 !important;
				border-radius: 50rpx;
				height: 70rpx;
				display: flex;
				align-items: center;

				.title_label {
					font-size: 28rpx;
					color: #999;
					padding-left: 12rpx;
				}
			}
		}

		.locat_content {
			margin: 24rpx;

			.tip_label {
				font-size: 28rpx;
				color: #999;
			}

			.current_position {
				background-color: #fff;
				border-radius: 20rpx;
				padding: 24rpx;
				margin: 24rpx 0;
				display: flex;
				justify-content: space-between;
				align-items: center;

				&_left {
					flex: 1;

					.left_address {
						font-size: 28rpx;
						margin-bottom: 12rpx;
					}

					.left_tip {
						font-size: 24rpx;
						color: #999;

					}
				}

				&_right {
					margin-left: 12rpx;
					color: #007cff;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.example-body {
				margin: 24rpx;

				:deep(.uni-progress-bar) {
					display: none;
				}

				.pic_text {
					display: flex;
					align-items: center;
					flex-direction: column;
					justify-content: center;
					font-size: 24rpx;
					color: #999;
				}
			}
		}

		.btn_word {
			padding: 24rpx 48rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 2;

			:deep(button:after) {
				border: none !important;
			}

			.btn_bor {
				width: 100%;
				font-size: 32rpx;
				border-radius: 50rpx;
				background-color: #007cff;
			}
		}
	}
</style>